import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:jxchmz/%E9%94%80%E5%94%AE/%E9%94%80%E5%94%AE%E8%AE%B0%E5%BD%95/SalNotesXiangQing.dart';
import 'package:jxchmz/API/%E5%BA%93%E5%AD%98%E7%AE%A1%E7%90%86/KuCunManager.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/GetxTools.dart';
import 'package:jxchmz/Getx%E5%B7%A5%E5%85%B7/KSProgressDialog.dart';

class SalNotes extends StatefulWidget {
  @override
  _SalNotesState createState() => new _SalNotesState();
}

class _SalNotesState extends State<SalNotes> {
  TextEditingController SearchController = new TextEditingController();
  String date = "";
  //年
  String Year = "";
  //月
  String Month = "";
//订单列表
  List OrderList = [];

  // 当前页数
  int _page = 1;

  // 是否还有
  bool _hasMore = true;

  // 滚动控制器
  ScrollController _scrollController = new ScrollController();

//页面加载完成时
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    date = DateTime.now().toString().substring(0, 7);
    // 监听滚动事件
    _scrollController.addListener(() {
      var maxScroll = _scrollController.position.maxScrollExtent;
      var pixel = _scrollController.position.pixels;
      if (maxScroll == pixel) {
        if (_hasMore) {
          _page++;
          GetlistSaleOrder(date);
        }
      }
    });

    Future.delayed(Duration.zero,(){
      GetlistSaleOrder(date);
    });
    setState(() {});
  }

  ///页面卸载
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  ///当 State 被暂时从视图树中移除时，会调用这个方法，同时页面切换时，也会调用。
  @override
  void deactivate() {
    // TODO: implement dispose
    super.deactivate();
  }

  ///在 initState() 之后调用，当 State 对象的依赖关系发生变化时，该方法被调用，初始化时也会调用。
  @override
  void didChangeDependencies() {
    // TODO: implement didChangeDependencies
    super.didChangeDependencies();
  }

  // TODO: add state variables and methods
  @override
  Widget build(BuildContext context) {
    // TODO: add widget build method
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: CupertinoSearchTextField(
          controller: SearchController,
          placeholder: "Enterthetrackingnumbertosearch".tr,
          placeholderStyle: TextStyle(fontSize: 13, color: Colors.black38),
        ),
        centerTitle: true,
        elevation: 0,
        iconTheme: IconThemeData(color: Colors.black),
        actions: [
          TextButton(
              onPressed: () {
                //搜索事件
                SearchOrder();
              },
              child: Text(
                "Search".tr,
                style: TextStyle(color: Colors.black),
              ))
        ],
      ),
      body: Container(
          padding: EdgeInsets.only(left: 15, right: 15),
          child: Column(
            children: [
              //选择日期
              Container(
                child: TextButton(
                  child: Row(
                    children: [
                      Text(
                        date.isEmpty ? "Selectadate".tr : date,
                        style: TextStyle(color: Colors.black),
                      ),
                      Icon(
                        Icons.arrow_drop_down,
                        color: Colors.black,
                      )
                    ],
                  ),
                  onPressed: () {
                    showdata(context);
                  },
                ),
              ),
              Expanded(
                child: ListView.separated(
                  itemCount: OrderList.length,
                  controller: _scrollController,
                  itemBuilder: (context, index) {
                    return ListTile(
                      title: Column(
                        children: [
                          Row(
                            children: [
                              Container(
                                child: Text(
                                  "Salestrackingnumber".tr+":${OrderList[index]['billNo']}",
                                  style: TextStyle(fontSize: 13),
                                ),
                              ),
                              Container(
                                child: Text("${OrderList[index]['billDate']}", style: TextStyle(fontSize: 13, color: Colors.black38)),
                              ),
                            ],
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          ),
                          Container(
                            height: 5,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Container(
                                child: Text("Outboundquantity".tr+":${OrderList[index]['outQty'].toInt().toString()}", style: TextStyle(fontSize: 13)),
                              ),
                              Container(
                                child: Text("Thenumberofreturns".tr+":${OrderList[index]['settleQty']}", style: TextStyle(fontSize: 13)),
                              )
                            ],
                          ),
                          Container(
                            height: 5,
                          ),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Container(
                                child: Text(
                                    "Auditstatus".tr+":${OrderList[index]['approvalResultType'] == 0 || OrderList[index]['approvalResultType'] == null ? "Underreview".tr : OrderList[index]['approvalResultType'] == 1 ? "Approved".tr : "Failed".tr}",
                                    style: TextStyle(fontSize: 13,color:OrderList[index]['approvalResultType'] == 0 || OrderList[index]['approvalResultType'] == null ?Colors.orange:OrderList[index]['approvalResultType'] == 1?Colors.green:Colors.red)),
                              ),
                              Container(
                                child: Text("Approvalopinions".tr+":${OrderList[index]['approvalRemark']}", style: TextStyle(fontSize: 13)),
                              )
                            ],
                          ),
                          Container(
                            height: 5,
                          ),
                          Row(
                            children: [
                              Container(
                                child: Text(
                                  "1",
                                  style: TextStyle(color: Colors.white),
                                ),
                              ),
                              Container(
                                child: MaterialButton(
                                  shape: const RoundedRectangleBorder(
                                    //边框圆角
                                    borderRadius: BorderRadius.all(
                                      Radius.circular(15),
                                    ),
                                  ),
                                  child: Text(
                                    "detail".tr,
                                    style: TextStyle(color: Colors.white, fontSize: 13),
                                  ),
                                  onPressed: () {
                                    //进入详情
                                    Get.to(SalNotesXiangQing(),arguments: {"Data":OrderList[index]});
                                  },
                                  color: Colors.blue,
                                ),
                                width: 60,
                                height: 25,
                                alignment: Alignment.centerRight,
                              ),
                            ],
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          )
                        ],
                      ),
                    );
                  },
                  separatorBuilder: (context, index) {
                    return Divider();
                  },
                ),
              )
            ],
          )),
    );
  }

  //弹窗选择日期
  showdata(context) async {
    GetStorage storage = new GetStorage();
    var Language = json.decode(await storage.read("Langage"));
    print("语言:$Language");
    List CodeList = [];
    CodeList = Language['LangageCode'].split("-");
    DateTime? SelectDate =
        await showDatePicker(context: context, initialDate: DateTime.now(), lastDate: DateTime.now(), firstDate: DateTime(1900, 01, 01),locale:  Locale(CodeList[0], CodeList[1]));
    date = SelectDate.toString().substring(0, 7);
    Year = date.substring(0,4);
    Month = date.substring(5,7);
    //获取销售订单
    SearchOrder();
    setState(() {});
  }

  //获取销售订单
  GetlistSaleOrder(dateTime) async {

    //取出本地个人信息
    GetStorage getStorage = new GetStorage();
    var Userid = json.decode(getStorage.read("User"))['user']['userId'];
    int permissions = getStorage.read("permissions");
    var data;
    //搜索参数
    if(permissions==2){
      data = {
        "pageNum": _page,
        "pageSize": 10,
        "reasonable": false,
        "appDate":dateTime
      };
    }else{
      data = {
        "pageNum": _page,
        "pageSize": 10,
        "reasonable": false,
        "operator":Userid,
        "appDate":dateTime
      };
    }
    KSProgressDialog().LoadingToast("Loading".tr, context);
    var ResponseData = await KuCunManager().GetSaleOrder(data);
    KSProgressDialog().CloseLoading();
    if (ResponseData['code'] == 200) {
      var List = ResponseData['rows'];
      if (List.length <= 0) {
        // 关闭加载
        this._hasMore = false;
      } else {
        List.forEach((element) {
          OrderList.add(element);
        });
      }
    } else {
      new GetxTools().ErrorToast("Failedtogetsalesorderinformation".tr);
    }
    setState(() {});
  }

  //搜索事件
  SearchOrder() {
    _page = 1;
    _hasMore = true;
    OrderList = [];
    GetlistSaleOrder(date);
  }
}
